/**
 * OM拨打电话service
 *
 */
define(['app','ext'], function( app ) {
    'use strict';

    app.factory('omcall', ['ext','dataFactoryCRM','$rootScope', function ( ext, dataFactoryCRM, $rootScope ) {
        var omcall = {state:-2,Ws:false,Maxtry:1,wsAddr:'',tm:1000*240,debug:true};

        omcall.c = function( _msg ){
            //console.log( _msg );
        }
        omcall.agent = function( d ){
            if( this.Ws ){
                this.Ws.send( JSON.stringify( d ) );
            }
        }

        omcall.connect = function(){
            if( !ext.ext || !ext.omid ){
                return false;
            }

            if( this.Ws ){
                return this.Ws;
            }
            else if( !this.Ws && this.Maxtry ){
                var _obj = this;
                this.Maxtry--;
                this.Ws = new WebSocket( this.wsAddr + "?omID="+ext.omid+"&subID="+ext.ext+"&UID="+ext.user_id);
                this.Ws.onopen = function() {
                        _obj.Maxtry = 5;
                        ext.login();
                        _obj.state = 0;
                        setTimeout(function(){  _obj.heartLine();},_obj.tm );
                    };

                this.Ws.onerror = function( error ){
                    _obj.handle('notify', 'error');
                };

                this.Ws.onmessage = function (evt) {
                    _obj.c('ws接收到消息，data:');
                    _obj.c( evt.data);
                    _obj.handle('msg', evt.data);
                };
                this.Ws.onclose = function() {
                    _obj.handle('notify', 'close');
                };
            }
            else{
                this.c("Ws  connect error");
                this.handle('notify', 'error');
            }
        }

        omcall.initExt = function( _ext ){
            if( !_ext )
                return;
            else{
                ext.user_id = _ext.uid;
                ext.ext = _ext.subphone;
                ext.omid = _ext.omid;
                ext.ipaddr = _ext.ipaddr;
                this.wsAddr = "ws://" + _ext.ipaddr + '/ws';
                this.state = -1;
                this.connect();
                ext.getCalls();
            }
        }

        omcall.heartLine = function(){
            if( !this.Ws )
                return false;
            else{
                var ping = {};
                ping.op = 'ping';
                ping.data = 'pong';
                this.Ws.send( JSON.stringify( ping ) );
            }
        }

        omcall.handle = function( _type, _data ){
            if( 'msg' == _type ){
                try{
                    var a = null;
                    a = JSON.parse( _data );
                    if( typeof a.rcode !== "undefined"  ){
                        if( a.rcode < 1 ){
                            return false;
                        }
                    }
                    if( 'init' == a.op ){
                        this.Ws.send({op: a.op,data:a.data,hzcf:1} );
                        ext.line_id = a.data.lineid;
                    }
                    else if( 'answer' == a.op || 'answered' == a.op ){
                        if( a.data.outer ){
                             ext.outer = a.data.outer;
                             ext.visitor = false;
                        }
                        else if( a.data.visitor ){
                            ext.outer = false ;
                            ext.visitor = a.data.visitor;
                        }
                        else{
                            ext.outer = false;
                            ext.visitor = false;
                        }
                    }
                    else if( 'cdr' == a.op || 'bye' == a.op){
                        if( 'cdr' == a.op && a.rcode )
                            ext.cdr( a.data );
                        ext.area = '';
                    }
                    else if( 'incoming' == a.op  ){
                        ext.incall( a.data['area'] );
                        // incoming call
                        //chrome.tabs.sendRequest(c_tab_id ,{op: a.op,data:a.data,exts:a.exts,hzcf:1},  function(response) {});
                        //hzcf_notify({title:'来电',img:'call.png',msg:a.data['area'] + ' '+ a.data['from'] }, true, 5000);
                    }
                    else if( 'offline' == a.op  ){
                        ext.offline();
                        //chrome.tabs.sendRequest(c_tab_id ,{op:a.op,data:a.msg,hzcf:1},  function(response) {});
                    }
                    else if('dail' == a.op){
                        ext.area = a.area;
                    }
                    else if('extchange' == a.op ){
                        //
                    }
                    else if('broadcast' == a.op ){
                        //hzcf_notify({title:'广播消息',img:'broadcast.png',msg:a.data }, false, 2000);
                    }
                    $rootScope.$broadcast('ST', a.op );
                 }catch(e){
                    this.c( e );
                    this.c("推送消息解析失败:" + _data );
                }
            }
            else if('notify' == _type ){
                if('close' == _data || 'error' == _data ){
                    $rootScope.$broadcast('ST',  _data );
                    this.Ws = null;
                    if( this.Maxtry ){
                        setTimeout(function(){
                            //omcall.connect();
                        },5000);
                    }
                    omcall.state = -1;
                    ext.offline();
                }
            }
        }

        return omcall;
    }]);

    //电话拨打 directive
    app.directive('callctl', ['omcall','ext','$rootScope','$interval',function (omcall, ext, $rootScope,$interval ){

        function link($scope, element, attrs ){
            var callState = {error:-2,close:-1,idle:0,busy:1,dail:1,call:2,incall:3};
            $scope.state = callState.error;
            $scope.ext  = ext.ext;
            $scope.ctime = ext.ctime;
            $scope.area = '';
            $scope.phone = '';
            $scope.calls = false;
            $scope.Connected = false;
            $scope.user = null;

            $('#phone_status_bar').popup({ on: 'click',inline: false,hoverable: true,position: 'bottom center', visible: 'hidden'});

            var stop;
            $scope.loadcalls = function(){
                 ext.getCalls().then(function(d){
                    if( d && d.rcode ){$scope.calls = d.data.out;}
                    else { $scope.states = "获取通话记录失败";}
                });
            }

            if( sessionStorage && sessionStorage.username  && sessionStorage.ext){
                var extdata = JSON.parse( sessionStorage.ext );
                omcall.initExt(  extdata );
                $scope.loadcalls();
                $scope.Connected = true;
            }
            $scope.stoptm = function(){
                if (angular.isDefined(stop)) {
                    $interval.cancel(stop);
                    stop = undefined;
                  }
              };

            $rootScope.$on('ST', function( scope, data ) {
                if('idle' == data ){
                    $scope.state = callState.idle;
                    $scope.phone = '';
                }
                else if( 'init' == data ){
                    $scope.Connected = true;
                    $scope.state = callState.idle;
                    $scope.loadcalls();
                }
                else if('dail' == data){
                    if( callState.dail !== $scope.state ){
                        $scope.area = ext.area;
                        $scope.state = callState.dail;
                        $scope.ctime = 0;
                    }
                }
                else if('answered' == data ){
                    $scope.state = callState.call;
                    stop = $interval(function() {
                    if ( $scope.state == callState.call ) {
                        $scope.ctime++;
                    } else {
                      $scope.stoptm( stop );
                    }
                  }, 1000);
                }
                else if( 'cdr' == data || 'bye' == data){
                    $scope.clear();
                    if( 'cdr' == data ){
                        if( !$scope.calls )
                            $scope.calls = array();
                        else
                            $scope.calls.pop();
                        $scope.calls.unshift( ext._cdr );
                        ext._cdr = false;
                    }
                    ext.hangup();
                }
                else if('incoming' == data ){
                    $scope.state = callState.incall;
                    $scope.area = ext.area;
                    $scope.phone = ext.phone;
                }
                else if('close' == data ){
                    $scope.state = callState.close;
                    $scope.states = '链接被关闭';
                    $scope.area = '';
                }
                else if('error' == data ){
                    $scope.state = callState.error;
                    $scope.states = '数据发送错误';
                }
            });

            $rootScope.$on('$destroy', function() {
                $scope.stoptm();
            });

            $scope.dail = function(){
                if( $scope.phone && ( $scope.phone.length == 11 || $scope.phone.length == 12 ) ){
                    var _callData = {};
                    _callData.op = 'dail';
                    _callData.data = $scope.phone;
                    ext.call($scope.phone, '');
                    this.state = 1;
                    omcall.agent( _callData );
                }
            }

            $scope.connect = function (){
                omcall.connect();
            }

            $scope.clear = function(){
                $scope.state = 0;
                $scope.phone = '';
                $scope.ctime = 0;
            }

            $scope.hangup = function(){
                if( $scope.state == callState.call ){
                    var _callData = {};
                    $scope.area = '';
                    _callData.op = 'clear';
                    if( ext.visitor )
                        _callData.vid = ext.visitor['id'];
                    if( ext.outer )
                        _callData.oid = ext.outer['id'];
                    omcall.agent( _callData );
                }
                else{

                }
            }
            $scope.pickup = function(){
                //
            }

            //来电转接
            $scope.transfer = function(){
            }

            $scope.showcall = function(){
                //
            }
        }

        return {
        restrict: 'E',
        templateUrl: 'views/directive/callctl.html',
        scope: {},
        link: link
    }
    }]);
});
